{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "4883387b-28de-4ff1-8db3-7a50f54f3f62",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 导入必要的库\n",
    "import math\n",
    "\n",
    "# 1. 输入某年某月某日，判断这一天是这一年的第几天\n",
    "def day_of_year(year, month, day):\n",
    "    from datetime import datetime\n",
    "    start_of_year = datetime(year, 1, 1)\n",
    "    given_date = datetime(year, month, day)\n",
    "    delta = given_date - start_of_year\n",
    "    return delta.days + 1  # 加1是因为我们想要包含这一天本身\n",
    "\n",
    "# 2. 判断1000中有多少个素数，并输出所有素数\n",
    "def count_primes_below_1000():\n",
    "    primes = []\n",
    "    for num in range(2, 1000):\n",
    "        if all(num % i != 0 for i in range(2, int(math.sqrt(num)) + 1)):\n",
    "            primes.append(num)\n",
    "    return len(primes), primes\n",
    " \n",
    "# 3. 利用条件运算符的嵌套来完成此题\n",
    "def grade_to_letter(score):\n",
    "    return 'A' if score >= 90 else ('B' if 60 <= score < 90 else 'C')\n",
    "\n",
    "# 4. 输入一行字符串，分别统计出其中英文字母、空格、数字和其它字符的个数\n",
    "def count_characters(s):\n",
    "    letters, spaces, digits, others = 0, 0, 0, 0\n",
    "    for char in s:\n",
    "        if char.isalpha():\n",
    "            letters += 1\n",
    "        elif char.isspace():\n",
    "            spaces += 1\n",
    "        elif char.isdigit():\n",
    "            digits += 1\n",
    "        else:\n",
    "            others += 1\n",
    "    return letters, spaces, digits, others\n",
    "\n",
    "# 5. 找出1000以内的所有完数\n",
    "def find_perfect_numbers(limit):\n",
    "    perfect_numbers = []\n",
    "    for num in range(1, limit + 1):\n",
    "        factors = [i for i in range(1, num) if num % i == 0]\n",
    "        if sum(factors) == num:\n",
    "            perfect_numbers.append(num)\n",
    "    return perfect_numbers\n",
    "\n",
    "# 6. 输入任意数N，求1+2!+3!+...+N!的值\n",
    "def factorial_sum(N):\n",
    "    return sum(math.factorial(i) for i in range(1, N + 1))\n",
    "\n",
    "# 7. 输入任意奇数N，打印出菱形图案\n",
    "def print_diamond(N):\n",
    "    assert N % 2 == 1, \"N必须是奇数\"\n",
    "    mid = N // 2\n",
    "    for i in range(N):\n",
    "        if i <= mid:\n",
    "            print('*' * (2 * i + 1))\n",
    "        else:\n",
    "            print('*' * (2 * (N - i) - 1))\n",
    "\n",
    "# 8. 对10个数进行排序\n",
    "def sort_numbers(numbers):\n",
    "    return sorted(numbers)\n",
    "\n",
    "# 9. 将一个数插入已排序数组中\n",
    "def insert_into_sorted_array(arr, num):\n",
    "    for i in range(len(arr)):\n",
    "        if num < arr[i]:\n",
    "            arr.insert(i, num)\n",
    "            break\n",
    "    else:\n",
    "        arr.append(num)\n",
    "    return arr\n",
    "\n",
    "# 10. 约瑟夫环问题\n",
    "def josephus_problem(n, k):\n",
    "    people = list(range(1, n + 1))\n",
    "    index = 0\n",
    "    while len(people) > 1:\n",
    "        index = (index + k - 1) % len(people)\n",
    "        people.pop(index)\n",
    "    return people[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "c9cbe165-5859-4a69-9ace-30626f3c681d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "请选择要解答的题目编号：\n",
      "1. Day of year\n",
      "2. Count primes below 1000\n",
      "3. Grade to letter\n",
      "4. Count characters\n",
      "5. Find perfect numbers\n",
      "6. Factorial sum\n",
      "7. Print diamond\n",
      "8. Sort numbers\n",
      "9. Insert into sorted array\n",
      "10. Josephus problem\n"
     ]
    },
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "请输入题目编号： 7\n",
      "请输入奇数N（控制行数和本行的星数）： 9\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "*\n",
      "***\n",
      "*****\n",
      "*******\n",
      "*********\n",
      "*******\n",
      "*****\n",
      "***\n",
      "*\n"
     ]
    }
   ],
   "source": [
    "# 主函数，用于交互选择题目\n",
    "def main():\n",
    "    print(\"请选择要解答的题目编号：\")\n",
    "    for i, func_name in enumerate([\n",
    "        \"day_of_year\", \"count_primes_below_1000\", \"grade_to_letter\",\n",
    "        \"count_characters\", \"find_perfect_numbers\", \"factorial_sum\",\n",
    "        \"print_diamond\", \"sort_numbers\", \"insert_into_sorted_array\",\n",
    "        \"josephus_problem\"\n",
    "    ], start=1):\n",
    "        print(f\"{i}. {func_name.replace('_', ' ').capitalize()}\")\n",
    "    \n",
    "    choice = input(\"请输入题目编号：\")\n",
    "    \n",
    "    try:\n",
    "        choice = int(choice)\n",
    "        if 1 <= choice <= 10:\n",
    "            if choice == 7:\n",
    "                N = int(input(\"请输入奇数N（控制行数和本行的星数）：\"))\n",
    "                print_diamond(N)\n",
    "            else:\n",
    "                if choice in [2, 5, 8, 10]:\n",
    "                    # 需要额外输入的函数\n",
    "                    if choice == 2:\n",
    "                        num_primes, primes = count_primes_below_1000()  # 直接调用函数\n",
    "                        print(f\"1000以内有{num_primes}个素数：{primes}\")\n",
    "                    elif choice == 5:\n",
    "                        perfect_numbers = find_perfect_numbers(1000)\n",
    "                        print(f\"1000以内的完数有：{perfect_numbers}\")\n",
    "                    elif choice == 8:\n",
    "                        numbers = list(map(int, input(\"请输入10个数，用空格分隔：\").split()))\n",
    "                        sorted_numbers = sort_numbers(numbers)\n",
    "                        print(f\"排序后的数是：{sorted_numbers}\")\n",
    "                    elif choice == 10:\n",
    "                        n = int(input(\"请输入总人数n：\"))\n",
    "                        k = int(input(\"请输入报数的间隔k：\"))\n",
    "                        result = josephus_problem(n, k)\n",
    "                        print(f\"最后留下的是原来第{result}号的那位。\")\n",
    "                else:\n",
    "                    # 直接运行的函数\n",
    "                    if choice == 1:\n",
    "                        year, month, day = map(int, input(\"请输入年月日（用空格分隔）：\").split())\n",
    "                        print(f\"{year}年{month}月{day}日是这一年的第{day_of_year(year, month, day)}天。\")\n",
    "                    elif choice == 3:\n",
    "                        score = float(input(\"请输入学习成绩：\"))\n",
    "                        print(f\"学习成绩等级为：{grade_to_letter(score)}\")\n",
    "                    elif choice == 4:\n",
    "                        s = input(\"请输入一行字符串：\")\n",
    "                        letters, spaces, digits, others = count_characters(s)\n",
    "                        print(f\"英文字母个数：{letters}，空格个数：{spaces}，数字个数：{digits}，其它字符个数：{others}\")\n",
    "                    elif choice == 6:\n",
    "                        N = int(input(\"请输入任意数N：\"))\n",
    "                        print(f\"1+2!+3!+...+{N}!的值为：{factorial_sum(N)}\")\n",
    "                    elif choice == 9:\n",
    "                        arr = list(map(int, input(\"请输入已排序的数组（用空格分隔）：\").split()))\n",
    "                        num = int(input(\"请输入要插入的数：\"))\n",
    "                        new_arr = insert_into_sorted_array(arr[:], num)  # 使用arr[:]以避免修改原数组\n",
    "                        print(f\"插入后的数组为：{new_arr}\")\n",
    "        else:\n",
    "            print(\"无效的题目编号，请重新选择。\")\n",
    "    except ValueError:\n",
    "        print(\"请输入有效的数字编号。\")\n",
    " \n",
    "# 在Jupyter Notebook中调用主函数\n",
    "main()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9edef02a-0dbf-4603-a9d8-3407fb2887b1",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
